import React, { useState } from 'react';
import Web3 from 'web3';

const Login = () => {
  const [address, setAddress] = useState('');
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  const handleLogin = async () => {
    try {
      // 获取用户钱包地址
      const web3 = new Web3(window.ethereum);
      const accounts = await web3.eth.getAccounts();
      setAddress(accounts[0]);

      // 调用智能合约验证密码 (假设你已经将智能合约实例化)
      const isPasswordValid = await userListContract.methods
        .verifyPwd(username, password)
        .call();

      if (isPasswordValid) {
        // 登录成功，存储用户信息
        localStorage.setItem('address', address);
        localStorage.setItem('username', username);
        // 重定向到首页或个人中心
        window.location.href = '/';
      } else {
        alert('密码错误!');
      }
    } catch (error) {
      console.error('登录失败:', error);
    }
  };

  return (
    <div>
      <h1>登录</h1>
      <input
        type="text"
        placeholder="用户名"
        value={username}
        onChange={(e) => setUsername(e.target.value)}
      />
      <input
        type="password"
        placeholder="密码"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />
      <button onClick={handleLogin}>登录</button>
    </div>
  );
};

export default Login;